from transformers import AutoModelForCausalLM, AutoTokenizer
import time
model_name = r"C:\Users\strong\Desktop\fsdownload\Qwen2.5-0.5B"

start_time = time.time()
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype="auto",
    device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)

prompt = "你是谁"
messages = [
    {"role": "user", "content": prompt}
]
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True
)

model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

generated_ids = model.generate(
    **model_inputs,
    max_new_tokens=512,
    # temperature=0.01,  # 增加生成的随机性
    # do_sample=True,
    repetition_penalty=1.2  # 减少重复生成
)
generated_ids = [
    output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]

response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
end_time = time.time()
use_time = end_time - start_time
print(f'耗时{use_time}')
print(response)
#
# generated_ids = generated_ids[0][model_inputs.input_ids.shape[-1]:]  # 只保留新生成的部分
# response = tokenizer.decode(generated_ids, skip_special_tokens=True)
# print(response)

